<template>
    <!-- Main content -->
    <div>
        <div class="row">
            <div class="col-xs-12">
                <theme-box title="商户入驻维护">
                    <form class="form-inline" @submit.prevent v-el:form>
                        <form-input title="商户名称" :up-table="true" name="mchtName"></form-input>
                        <form-date-time title="申请开始时间" :up-table="true" name="crtTime1"></form-date-time>
                        <form-date-time title="申请结束时间" :up-table="true" name="crtTime2"></form-date-time>
                        <form-select title="审核状态" :up-table="true" :options="stateOptions" name="mchtstat"
                                     :sreach="true" id="mchtstat"></form-select>

                        <div style="float:right;margin-top:5px!important" class="button">
                            <button type="reset" @click="reset" class="btn btn-warning pull-right">重置</button>
                            <v-button theme="primary" @click="search" class="pull-right">查询</v-button>
                        </div>

                    </form>
                    <table class="table table-bordered table-striped" style="width:100%" v-el:table>
                    </table>
                </theme-box>
            </div>
            <!-- /.col -->
        </div>
        <modal-container title="修改" v-el:modal v-ref:modal class="edit-modal" theme="big">
            <form @submit.prevent @reset.prevent v-el:mform>
                <div class="modal-body revise-body">
                    <table-modal :item="item" :columns-set="columnsSet" :columns-num="2" v-ref:item></table-modal>

                </div>
                <div class="modal-footer">
                    <v-button data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                    <v-button theme="primary" type="submit">保存</v-button>
                </div>
            </form>
        </modal-container>

        <modal-container title="审核" v-el:review-modal v-ref:review-modal class="edit-modal" theme="small_window">
            <form @submit.prevent @reset.prevent v-el:review-mform>
                <div class="modal-body review-body">
                    <table-modal :item="item" :columns-set="columnsReviewSet" :columns-num="1"></table-modal>
                    <span style="margin-left:3%"><span class="required">*</span>审核方式</span>
                    <span style="margin-left:18%"><input type="radio" name="radio" value="" id="noPass"/>不通过</span>
                    <span style="margin-left:15%"><input type="radio" name="radio" value="" id="pass"/>通过</span>

                </div>
                <div class="modal-footer">
                    <v-button data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                    <v-button theme="primary" type="submit">提交</v-button>
                </div>
            </form>
        </modal-container>

        <modal-container title="详情" v-el:detail-modal v-ref:detail-modal class="edit-modal">
            <form @submit.prevent @reset.prevent v-el:detail-mform>
                <div class="modal-body">
                    <!-- <table-modal :item="item" :columns-set="columnsDetailSet"></table-modal> -->
                    <table class="table table-bordered table-hover">
                        <tr>
                            <td style="width:50%">商户名称</td>
                            <td>{{item.mchtName}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">商户类型</td>
                            <td>{{item.upperDictValue}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">商户主类型</td>
                            <td>{{item.dictValue}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">商户标志</td>
                            <td>
                                {{(item.mchtBusType == "1" && "有分店") || (item.mchtBusType == "0" && "无分店") || (item.mchtBusType == "3" && "代理商")|| (item.mchtBusType == "4" && "商圈")}}
                            </td>
                        </tr>
                        <tr>
                            <td style="width:50%">商户地址</td>
                            <td>{{item.mchtAddr}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">商户电话</td>
                            <td>{{item.mchtTel}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">抓取设备标志</td>
                            <td>{{item.equipFlag == 1 ? "不需要" : "需要"}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">营业执照</td>
                            <td>
                                <img class="table-avatar" :src="item.picUrl" style="width:30%">
                            </td>
                        </tr>
                        <tr>
                            <td style="width:50%">商区园区标识</td>
                            <td>{{item.streamDbt == "bussiness" ? "商区" : "园区"}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">负责人姓名</td>
                            <td>{{item.leadName}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">负责人电话</td>
                            <td>{{item.leadPhone}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">负责人身份证号</td>
                            <td>{{item.leadId}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">审核时间</td>
                            <td>{{item.auditTime}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">审核状态</td>
                            <td>
                                {{(item.mchtStat == "0" && "待审核") || (item.mchtStat == "1" && "已审核") || (item.mchtStat == "2" && "已拒绝")}}
                            </td>
                        </tr>
                        <tr>
                            <td style="width:50%">商户评级</td>
                            <td>{{item.rateLvl}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">营销比例</td>
                            <td>{{item.yqProp}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">营销结算比例</td>
                            <td>{{item.useProp}}</td>
                        </tr>
                    </table>
                </div>
                <div class="modal-footer">
                    <v-button class="pull--left" data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                </div>
            </form>
        </modal-container>
        <!-- /.row -->
    </div>
    <!-- /.content -->
</template>

<style lang="less" scoped>
    .form-inline .btn + .btn {
        margin-right: 10px;
    }

    /*.form-inline .form-group+.form-group {*/
    /*margin-left: 20px;*/
    /*}*/
</style>
<style scoped>

    .form-inline #mchtstat .control-label {
        margin-left: 0% !important;
    }
</style>

<script>
    //解决datatables弹窗警告
    $.fn.dataTable.ext.errMode = 'none';
    import {
        dateTime,
        createDataTable
    } from 'ui/collections/general.js'
    var serialize = require('form-serialize');
    import {dateFormat} from "lib/method.js"

    var dataTable;
    var columnsSet;
    export default {
        data: () => ({
            _array: [],
            item: {},
            columnsSet: [],
            mchtType: [],
            stateOptions: [{
                key: "所有状态",
                value: ""
            }, {
                key: "待审核",
                value: "0"
            }, {
                key: "已审核",
                value: "1"
            },{
                key: "已拒绝",
                value: "2"
            }],
            columnsReviewSet: [{
                title: "商户名称",
                data: "mchtName",
                edit: true,
                readonly: true,
                className: "operate",
            }, {
                title: "商户评级",
                data: "rateLvl",
                edit: true,
                className: "operate"
            },{
                title: "营销比例",
                data: "yqProp",
                edit: true,
                className: "operate"
            },{
                title: "营销结算比例",
                data: "useProp",
                edit: true,
                className: "operate"
            }],

        }),
        methods: {
            //还原弹出框位置
            resetBindDrag() {
                $("#noPass").prop("checked",false);
                $("#pass").prop('checked',false);
                this.$refs.reviewModal._resetBindDrag();
            },
            //查询按钮
            search: function (){
                dataTable.ajax.reload();
            },
            //重置按钮
            reset: function (){
                $(".form-inline")[0].reset();
                dataTable.ajax.reload();
            }
        },
        created() {
            columnsSet = [{
                title: "商户名称",
                data: "mchtName",
                edit: true,
                readonly: true,
                className: "operate",
            }, {
                title: "商户类型",
                className: "operate",
                visible:false,
                data: "upperDictId",
            }, {
                title: "商户类型",
                data: "upperDictValue",
                className: "operate",
            },{
                title: "商户主类型",
                data: "mchtType",
                visible:false,
                className: "operate",
            }, {
                title: "商户主类型",
                data: "dictValue",
                className: "operate",
            }, {
                title: "商户标志",
                data: "mchtBusType",
                visible:false,
                options: [{key: "有分店", value: "1"}, {key: "无分店", value: "0"},{key: "代理商", value: "3"},{key: "商圈", value: "4"}],
                className: "operate"
            }, {
                title: "营业执照",
                data: "picUrl",
                visible:false,
                img: true,
                upload:true,
                className: "operate",
                upload:true,
                render: function (data) {
                    return `<img class="table-avatar" src=` + data + `>`
                }
            }, {
                title: "商户地址",
                data: "mchtAddr",
                visible:false,
                edit: true,
                className: "operate",
            }, {
                title: "商户电话",
                data: "mchtTel",
                visible:false,
                edit: true,
                className: "operate",
            },  {
                title: "商区园区标识",
                data: "streamDbt",
                options: [{key: "商区", value: "business"}, {key: "园区", value: "park"}],
                className: "operate",
                render: function (data) {
                    return (data == "business") ? "商区" : "园区"
                }

            }, {
                title: "抓取设备标志",
                data: "equipFlag",
                options: [{key: "不需要", value: "1"}, {key: "需要", value: "0"}],
                className: "operate",
                render: function (data) {
                    return (data == 1) ? "不需要" : "需要"
                }
            }, {
                title: "负责人姓名",
                data: "leadName",
                visible:false,
                edit: true,
                className: "operate",
            }, {
                title: "负责人电话",
                data: "leadPhone",
                visible:false,
                edit: true,
                className: "operate",
            }, {
                title: "负责人身份证号",
                data: "leadId",
                visible:false,
                edit: true,
                className: "operate",
            },{
                title: "申请时间",
                data: "crtTime",
                className: "operate",
                render: function (data) {
                    return dateFormat(data)
                }
            }, {
                title: "审核状态",
                data: "mchtStat",
                className: "operate",
                render: function (data) {
                    var value;
                    if (data == "0") {
                        value = '待审核'
                    } else if (data == "1") {
                        value = '已审核'
                    } else {
                        value = "已拒绝"
                    }
                    return value;
                }
            }, {
                title: "相关操作",
                className: "operate",
                width: "160px",
                render: function (value, type, row) {
                    if (row.mchtStat == "0") {
                        return `
                    <button type="button" class="btn btn-primary btn-sm edit">修改</button>
                    <button type="button" class="btn btn-danger btn-sm review">审核</button>
                    <button type="button" class="btn btn-defalt btn-sm detail">详情</button>

                `
                    } else if (row.mchtStat == "2") {
                        return `
                    <button type="button" class="btn btn-primary btn-sm edit">修改</button>
                    <button type="button" class="btn btn-defalt btn-sm detail">详情</button>

                `
                    }
                    else {
                        return `
                    <button type="button" class="btn btn-defalt btn-sm detail">详情</button>
                `
                    }

                }
            }];
        },
        ready: async function () {
            dateTime({
                format: "yyyy-mm-dd",
                minView: "2",
                startDate: "",
                endDate: ""
            })
            this.$set("columnsSet", columnsSet)
            var mchtBusTypeWatch = function () {
            };
            var mcht_TypeWatch = function () {
            };
            var self = this;
            //创建dataTable
            dataTable = $(this.$els.table).DataTable({
                "columns": this.columnsSet, //定义列
                "ajax": async function (data, callback, settings) {
                    var page = [{
                        "name": "iDisplayStart",
                        "value": 1 + data.start / data.length
                    }, {
                        "name": "iDisplayLength",
                        "value": data.length
                    }];
                    //表单序列化数据
                    var _data = serialize(self.$els.form, {
                        hash: true,
                        disabled: true,
                        empty: true
                    });
                    _data.aoData = JSON.stringify(page);
                    //对申请日期进行数据处理
                    _data.crtTime1 = _data.crtTime1.replace(/-/g, "");
                    _data.crtTime2 = _data.crtTime2.replace(/-/g, "");
                    //判断日期
                    if(_data.crtTime1.length>0 && _data.crtTime2.length>0){
                        if(_data.crtTime1-_data.crtTime2 > 0){
                            Midway.alert({title: "操作提示", content: '申请开始时间不能大于申请结束时间'})
                            // return false
                        }
                    }else if(_data.crtTime1.length>0 && _data.crtTime2.length <=0){
                        Midway.alert({title: "操作提示", content: '申请结束时间不能为空'})
                        // return false
                    }else if(_data.crtTime1.length <= 0 && _data.crtTime2.length > 0){
                        Midway.alert({title: "操作提示", content: '申请开始时间不能为空'})
                        // return false
                    }

                    //发送请求
                    var result = await self.$post({
                        url: "/api/v1" + projectName_Url + "/plat/mcht/enterQuery",
                        data: _data,
                        method: "POST"
                    })
                    if (result.respCode != "00") {
                        Midway.alert({
                            title: "操作失败",
                            content: result.content
                        })
                    }
                    callback({
                        recordsTotal: result.content.total,
                        recordsFiltered: result.content.total,
                        data: result.content.list || []
                    })
                }
            });

            $(self.$el).on("click", ".edit", function () {
                var Row = $(this).closest('tr').get(0);
                const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                self.item = dataArray;
                dateTime()
                //请求商户类型
                self.$post({
                    url: "/api/v1" + projectName_Url + "/list/caterdict/back_type/0",
                    method:"GET"
                }).then(response => {
                    let list = response.content.info;
                    var _array = [];
                    for (let i = 0; i < list.length; i++) {
                        _array.push({value: list[i].value, key: list[i].key});
                    }
                    self.$set("columnsSet[1].options", _array)
                }, error => {});
                //请求商户主类型
                self.$post({
                    url: "/api/v1" + projectName_Url + "/list/caterdict/" + dataArray.upperDictId + '/0',
                    method: "GET"
                }).then(response => {
                    let list = response.content.info;
                    var _array = [];
                    for (let i = 0; i < list.length; i++) {
                        _array.push({value: list[i].dictId, key: list[i].dictValue});
                    }
                    self.$set("columnsSet[3].options", _array)
                }, error => {
                });
                //监听商户类型 请求商户主类型
                mcht_TypeWatch()
                mcht_TypeWatch = self.$refs.item.$watch("item.upperDictId", function (v) {
                    self.$post({
                        url: "/api/v1" + projectName_Url + "/list/caterdict/" + v + '/0',
                        method: "GET"
                    }).then(response => {
                        let list = response.content.info;
                        var _array = [];
                        for (let i = 0; i < list.length; i++) {
                            _array.push({value: list[i].dictId, key: list[i].dictValue});
                        }
                        self.$set("columnsSet[3].options", _array)
                    }, error => {
                    });
                });


                //商户类型 1   商户级别0 抓取标志1 商区园区 business
                if(self.item.mchtBusType == '3'){
                    self.columnsSet.find(data => data.data == "equipFlag").options = '';
                    self.columnsSet.find(data => data.data == "streamDbt").options = '';
                    self.columnsSet.find(data => data.data == "upperDictId").options = '';
                    self.columnsSet.find(data => data.data == "mchtType").options = '';
                }else{
                    self.columnsSet.find(data => data.data == "equipFlag").options = [
                        {key: "不需要", value: "1"},
                        {key: "需要", value: "0"}
                    ];
                    self.columnsSet.find(data => data.data == "streamDbt").options = [
                        {key: "商区", value: "business"},
                        {key: "园区", value: "park"}
                    ];
                }
                mchtBusTypeWatch()
                mchtBusTypeWatch = self.$refs.item.$watch("item.mchtBusType", function (v) {
                    if (v == '3') {
                        self.columnsSet.find(data => data.data == "equipFlag").options = '';
                        self.columnsSet.find(data => data.data == "streamDbt").options = '';
                        self.columnsSet.find(data => data.data == "upperDictId").options = '';
                        self.columnsSet.find(data => data.data == "mchtType").options = '';
                    } else {
                        self.columnsSet.find(data => data.data == "equipFlag").options = [
                            {key: "不需要", value: "1"},
                            {key: "需要", value: "0"}
                        ];
                        self.columnsSet.find(data => data.data == "streamDbt").options = [
                            {key: "商区", value: "business"},
                            {key: "园区", value: "park"}
                        ];
                    }
                });
                $(self.$els.mform).validate(self.item.valdate = {
                    async submitHandler() {
                        var form = self.$els.mform;
                        var _data = serialize(form, {hash: true, disabled: true, empty: true});
                        let formData = new FormData(form);
                        // return flase
                        if(_data.mchtBusType == '3'){
                            formData.append('mchtType',1)
                            formData.append('equipFlag',1)
                            formData.append('streamDbt','business')
                        }
                        formData.append('mchtName',self.item.mchtName)
                        var result = await self.$post({
                            url: "/api/v1" + projectName_Url + "/plat/mcht/upd",
                            data: formData,
                            method: "POST"
                        });
                        Midway.alert({title: "操作提示", content: result.errorInfo})

                        dataTable.ajax.reload(null, false);
                        $(self.$els.modal).modal('hide');
                        self.resetBindDrag()
                    },
                    rules: {
                        mchtName: {
                            required: true,
                            stringMaxLength: 64
                        },
                        upperDictId:{
                            required:true
                        },
                        mchtType: {
                            required: true,
                            maxlength: 32
                        },
                        mchtBusType: {
                            required: true
                        },
                        mchtAddr: {
                            required: true,
                            stringMaxLength: 128
                        },
                        mchtTel: {
                            required: true,
                            isPhone:true
                        },
                        busLicenPic: {
                            required: true,
                        },
                        leadName: {
                            required: true,
                            maxlength: 10
                        },
                        leadPhone: {
                            required: true,
                            isPhone: true
                        },
                        streamDbt: {
                            required: true,
                        },
                        leadId: {
                            required: true,
                            isIDCard:true
                        },
                        crtTime: {
                            required: true

                        },
                        rateLvl: {
                            required: true

                        },

                    }
                });
                $(self.$els.modal).modal('show');
            });


            $(self.$el).on("click", ".review", function () {
                var Row = $(this).closest('tr').get(0);
                const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                self.item = dataArray;
                dateTime()
                //点击审核  让第二行隐藏
                self.columnsReviewSet.find(data => data.data == "rateLvl").edit = false;
                self.columnsReviewSet.find(data => data.data == "yqProp").edit = false;
                self.columnsReviewSet.find(data => data.data == "useProp").edit = false;
                //点击通过 让第二行显示
                $("#pass").click(function () {
                    if(dataArray.mchtBusType != '3'){
                        self.columnsReviewSet.find(data => data.data == "rateLvl").edit = true;
                        self.columnsReviewSet.find(data => data.data == "yqProp").edit = true;
                        self.columnsReviewSet.find(data => data.data == "useProp").edit = true;
                    }
                })
                //点击不通过 让第二行不显示
                $("#noPass").click(function () {
                    self.columnsReviewSet.find(data => data.data == "rateLvl").edit = false;
                    self.columnsReviewSet.find(data => data.data == "yqProp").edit = false;
                    self.columnsReviewSet.find(data => data.data == "useProp").edit = false;
                })
                //审核通过传1  不通过传2
                var reviewStat;
                $(".review-body span input").click(function () {
                    if ($("#noPass").prop("checked")) {
                        reviewStat = 2;
                    }
                    if ($("#pass").prop("checked")) {
                        reviewStat = 1;
                    }
                })
                //点击关闭 审核方式清空
                $(".modal-footer .btn.btn-default").click(function(){
                    $("#noPass").prop("checked",false);
                    $("#pass").prop('checked',false);
                    self.resetBindDrag()
                });
                $(".modal-header .close span").click(function(){
                    $("#noPass").prop("checked",false);
                    $("#pass").prop('checked',false);
                    self.resetBindDrag()
                });
                //审核验证、保存、提交
                $(self.$els.reviewMform).validate(self.item.valdate = {
                    async submitHandler() {
                        var form = self.$els.reviewMform;
                        var _data = serialize(form, {hash: true, disabled: true, empty: true});
                        //判断单选框必须有一个被选中
                        var radios = $("input[name = 'radio']");
                        for (var i = 0; i < radios.length; i++) {
                            if($("#noPass").is(":checked") || $("#pass").is(":checked")) {

                            }
                            else{
                                Midway.alert({title: "操作提示", content:'审核方式必须选一个'});
                                return;
                            }
                        }
                        var oprId = JSON.parse(localStorage.getItem("id_token")).oprId;
                        _data.oprId = oprId;
                        _data.reviewStat = reviewStat
                        // 入驻：商户级别0 芸券比例 营销比例为0
                        if(dataArray.mchtBusType == '3'){
                            _data.rateLvl = 0;
                            _data.yqProp = 0;
                            _data.useProp = 0;

                        }
                        var result = await self.$post({
                            url: "/api/v1" + projectName_Url + "/plat/mcht/review",
                            data: _data,
                            method: "post"
                        }).then(response => {
                            let content = response.content;
                            let local = {
                                token: content.token,
                                usrName: content.usrName,
                                roleId: content.roleId,
                            };
                            localStorage.setItem("oprId", JSON.stringify(local.roleId));
                            self.$route.router.go('/merchantSettled/list');
                        }, error => {

                        });
                        dataTable.draw(false)
                        $(self.$els.reviewModal).modal('hide');
                        self.resetBindDrag()
                    },
                    rules: {
                        mchtName: {
                            required: true,
                            stringMaxLength: 64,
                            readonly: true,
                            disabled: true

                        },
                        rateLvl: {
                            required: true,
                            int:true,
                            reviewLvl: ["rateLvl"]
                        },
                        yqProp:{
                            required: true,
                            int:true,
                            min:0,
                            max:50
                        },
                        useProp:{
                            required: true,
                            int:true,
                            min:0,
                            max:50
                        },
                        reviewStat: {
                            required: true
                        }
                    }
                });
                $(self.$els.reviewModal).modal('show');
            });
            $(self.$el).on("click", ".detail", function () {
                var Row = $(this).closest('tr').get(0);
                const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                self.item = dataArray;
                if (dataArray.auditTime != null) {
                    dataArray.auditTime = dateFormat(dataArray.auditTime);
                }
                dateTime()
                $(self.$els.detailModal).modal('show');
            });
        },

    }
</script>
